package com.jarpackage.service;

import com.jarpackage.config.RepositoryConfig;
import com.jarpackage.model.Dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class RepositoryService {
    private static final Logger logger = LoggerFactory.getLogger(RepositoryService.class);
    private final RepositoryConfig repositoryConfig;

    public RepositoryService(RepositoryConfig repositoryConfig) {
        this.repositoryConfig = repositoryConfig;
    }

    public File downloadArtifact(Dependency dependency, String targetDir) throws IOException {
        String artifactPath = buildArtifactPath(dependency);
        String repositoryUrl = repositoryConfig.getUrl();
        if (!repositoryUrl.endsWith("/")) {
            repositoryUrl += "/";
        }

        URL url = new URL(repositoryUrl + artifactPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // Add Basic Authentication if credentials are provided
        if (repositoryConfig.getUsername() != null && !repositoryConfig.getUsername().isEmpty()) {
            String auth = repositoryConfig.getUsername() + ":" + repositoryConfig.getPassword();
            String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + encodedAuth);
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            File targetFile = new File(targetDir, dependency.getArtifactId() + "-" + dependency.getVersion() + "." + dependency.getType());
            Path targetPath = targetFile.toPath();

            try (InputStream in = connection.getInputStream()) {
                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
                logger.info("Successfully downloaded: {}", targetFile.getName());
                return targetFile;
            }
        } else {
            throw new IOException("Failed to download artifact: " + connection.getResponseMessage());
        }
    }

    private String buildArtifactPath(Dependency dependency) {
        StringBuilder path = new StringBuilder();
        path.append(dependency.getGroupId().replace('.', '/'));
        path.append('/');
        path.append(dependency.getArtifactId());
        path.append('/');
        path.append(dependency.getVersion());
        path.append('/');
        path.append(dependency.getArtifactId());
        path.append('-');
        path.append(dependency.getVersion());
        
        if (dependency.getClassifier() != null && !dependency.getClassifier().isEmpty()) {
            path.append('-');
            path.append(dependency.getClassifier());
        }
        
        path.append('.');
        path.append(dependency.getType());
        
        return path.toString();
    }
}